<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="OrgMainForm" ref="formRef">
          <a-row>
            <a-col :span="8">
              <a-form-item label="*机构编码" v-bind="validateInfos.orgCode" id="OrgMainForm-orgCode" name="orgCode">
                <a-input v-model:value="formData.orgCode" placeholder="请输入*机构编码" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*机构级别" v-bind="validateInfos.orgLevel" id="OrgMainForm-orgLevel" name="orgLevel">
                <j-dict-select-tag v-model:value="formData.orgLevel" dictCode="org_level" placeholder="请选择*机构级别" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="上级机构" v-bind="validateInfos.parentOrg" id="OrgMainForm-parentOrg" name="parentOrg">
                <j-search-select v-model:value="formData.parentOrg" dict="org_main where data_status='ysx',full_name,org_code" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*机构全称" v-bind="validateInfos.fullName" id="OrgMainForm-fullName" name="fullName">
                <a-input v-model:value="formData.fullName" placeholder="请输入*机构全称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="机构简称" v-bind="validateInfos.name" id="OrgMainForm-name" name="name">
                <a-input v-model:value="formData.name" placeholder="请输入机构简称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*机构类型" v-bind="validateInfos.orgType" id="OrgMainForm-orgType" name="orgType">
                <j-dict-select-tag v-model:value="formData.orgType" dictCode="org_type" placeholder="请选择*机构类型" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*社会统一信用代码" v-bind="validateInfos.socialCredit" id="OrgMainForm-socialCredit" name="socialCredit">
                <a-input v-model:value="formData.socialCredit" placeholder="请输入*社会统一信用代码" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*成立日期" v-bind="validateInfos.establishDate" id="OrgMainForm-establishDate" name="establishDate">
                <a-date-picker
                  placeholder="请选择*成立日期"
                  v-model:value="formData.establishDate"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*国家" v-bind="validateInfos.country" id="OrgMainForm-country" name="country">
                <a-input v-model:value="formData.country" placeholder="请输入*国家" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*省" v-bind="validateInfos.pro" id="OrgMainForm-pro" name="pro">
                <a-input v-model:value="formData.pro" placeholder="请输入*省" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="市" v-bind="validateInfos.city" id="OrgMainForm-city" name="city">
                <a-input v-model:value="formData.city" placeholder="请输入市" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="机构地址" v-bind="validateInfos.address" id="OrgMainForm-address" name="address">
                <a-input v-model:value="formData.address" placeholder="请输入机构地址" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*法定代表人" v-bind="validateInfos.contacter" id="OrgMainForm-contacter" name="contacter">
                <a-input v-model:value="formData.contacter" placeholder="请输入*法定代表人" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="联系电话" v-bind="validateInfos.contactPhone" id="OrgMainForm-contactPhone" name="contactPhone">
                <a-input v-model:value="formData.contactPhone" placeholder="请输入联系电话" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="邮政编码" v-bind="validateInfos.yzCode" id="OrgMainForm-yzCode" name="yzCode">
                <a-input v-model:value="formData.yzCode" placeholder="请输入邮政编码" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="*计税方法" v-bind="validateInfos.taxMethod" id="OrgMainForm-taxMethod" name="taxMethod">
                <j-popup
                  placeholder="请选择*计税方法"
                  v-model:value="formData.taxMethod"
                  code="tax_method"
                  :fieldConfig="[
                    { source: 'tax_method', target: 'taxMethod' },
                    { source: 'tax_rate', target: 'taxRate' },
                    { source: 'service_tax_rate', target: 'serviceTaxRate' },
                  ]"
                  :multi="true"
                  :setFieldsValue="setFieldsValue"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="税率" v-bind="validateInfos.taxRate" id="OrgMainForm-taxRate" name="taxRate">
                <a-input v-model:value="formData.taxRate" placeholder="请输入税率" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="服务型税率" v-bind="validateInfos.serviceTaxRate" id="OrgMainForm-serviceTaxRate" name="serviceTaxRate">
                <a-input v-model:value="formData.serviceTaxRate" placeholder="请输入服务型税率" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="是否市区机构" v-bind="validateInfos.isCityOrg" id="OrgMainForm-isCityOrg" name="isCityOrg">
                <j-dict-select-tag v-model:value="formData.isCityOrg" dictCode="yn" placeholder="请选择是否市区机构" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="是否允许关联物料" v-bind="validateInfos.isSynMaterial" id="OrgMainForm-isSynMaterial" name="isSynMaterial">
                <j-dict-select-tag v-model:value="formData.isSynMaterial" dictCode="yn" placeholder="请选择是否允许关联物料" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="数据状态" v-bind="validateInfos.dataStatus" id="OrgMainForm-dataStatus" name="dataStatus">
                <j-dict-select-tag v-model:value="formData.dataStatus" dictCode="data_status" placeholder="请选择数据状态" disabled allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="机构-供应商银行信息" key="orgBank" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="orgBankTableRef"
          :loading="orgBankTable.loading"
          :columns="orgBankTable.columns"
          :dataSource="orgBankTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryOrgBankListByMainId, queryDataById, saveOrUpdate } from '../OrgMain.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { orgBankColumns } from '../OrgMain.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JPopup from '/@/components/Form/src/jeecg/components/JPopup.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: 'OrgMainForm',
    components: {
      JDictSelectTag,
      JSearchSelect,
      JPopup,
      JVxeTable,
      JFormContainer,
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const loading = ref(false);
      const formRef = ref();
      const orgBankTableRef = ref();
      const orgBankTable = reactive<Record<string, any>>({
        loading: false,
        columns: orgBankColumns,
        dataSource: [],
      });
      const activeKey = ref('orgBank');
      const formData = reactive<Record<string, any>>({
        id: '',
        orgCode: '',
        orgLevel: '',
        parentOrg: '',
        fullName: '',
        name: '',
        orgType: '',
        socialCredit: '',
        establishDate: '',
        country: '',
        pro: '',
        city: '',
        address: '',
        contacter: '',
        contactPhone: '',
        yzCode: '',
        taxMethod: '',
        taxRate: '',
        serviceTaxRate: '',
        isCityOrg: '',
        isSynMaterial: '',
        dataStatus: 'cg',
      });

      //表单验证
      const validatorRules = reactive({});
      const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 5 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
      };

      // 表单禁用
      const disabled = computed(() => {
        if (props.formBpm === true) {
          if (props.formData.disabled === false) {
            return false;
          } else {
            return true;
          }
        }
        return props.formDisabled;
      });

      function add() {
        resetFields();
        orgBankTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const orgBankDataList = await queryOrgBankListByMainId(row['id']);
        orgBankTable.dataSource = [...orgBankDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if (row.hasOwnProperty(key)) {
            tmpData[key] = row[key];
          }
        });
        //赋值
        Object.assign(formData, tmpData);
      }

      const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
        orgBank: orgBankTableRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch ({ errorFields }) {
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData));
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values);
        const isUpdate = values.id ? true : false;
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }

      function setFieldsValue(values) {
        if (values) {
          Object.keys(values).map((k) => {
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      return {
        orgBankTableRef,
        orgBankTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      };
    },
  });
</script>
<style lang="less" scoped></style>
